package com.xunsiya.common.config.util;

import com.xunsiya.tools.common.cmd.ExecResult;
import com.xunsiya.tools.common.cmd.ExecUtil;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 视频截图工具<br/>
 * 对视频的第10秒处自动截取一张图片
 * 
 * @author zhangxw
 * 
 */
public final class VideoCaptureUtil {
    
    /**
     * 日誌
     */
    private static Logger log = Logger.getLogger(VideoCaptureUtil.class);

    /**
     * 视频截图
     * 
     * @param videoPath
     *            视频文件路径
     * @param captureImgFileName
     *            截图存放路径
     * @return 返回错误信息，若是null，表示没有错误信息
     */
    public static String captureImageAndGetBasicInfo(String videoPath, String captureImgFileName, int intervalTime) {
        
        String errMsg = null;
        
        if (!new File(videoPath).exists()) {
            errMsg =  "视频文件不存在";
            
            return errMsg;
        }

        List<String> windowCaptionCommandList = new ArrayList<>();
        windowCaptionCommandList.add("ffmpeg");
        windowCaptionCommandList.add("-ss");
        windowCaptionCommandList.add("" + intervalTime);
        windowCaptionCommandList.add("-i");
        windowCaptionCommandList.add(videoPath);
        // 强制替换已经存在的文件
        windowCaptionCommandList.add("-y");
        windowCaptionCommandList.add("-f");
        windowCaptionCommandList.add("image2");
        windowCaptionCommandList.add("-vframes");
        windowCaptionCommandList.add("1");
        windowCaptionCommandList.add(captureImgFileName);
        ExecResult result = null;
        try {
            result = ExecUtil.runCommand(windowCaptionCommandList, -1, null,null);
        } catch (IOException | InterruptedException e) {
            log.error("错误", e);
        }
        // 判断为空
        if (result == null) {
            return null;
        }

        switch (result.getExitValue()) {
        case ConstantInfo.ERROR_EXIT:
            errMsg = "截图进程非正常退出";
            break;
        case ConstantInfo.NORMAL_EXIT:
            String s = result.getResult();
            if(null!=s){
                Matcher matcher = invalidCapturePatt.matcher(s);
                if(matcher.find()){
                    errMsg = "不是视频文件或者视频的格式不支持";
                }
            }else if(!new File(captureImgFileName).exists()){
                errMsg =  "未知的错误，导致截图文件不存在";
            }
            break;
        case ConstantInfo.TIMEOUT_EXIT:
            errMsg = "截图超时，截图进程提前退出";
            break;
        default:
            break;
        }
        
        return errMsg;
    }

    /** 判断截图是否出现异常信息 */
    private static Pattern invalidCapturePatt = Pattern.compile("Error|Invalid");
}
